Mongoose
In this course, we will use a library called Mongoose to work with MongoDB in Express apps.
Mongoose is an object document mapping (ODM) that sits on top of Node MongoDB driver.
First, you should add mongoose as a dependency:
yarn add mongoose
Next, you should connect mongoose client to your MongoDB cluster:
import mongoose from "mongoose";
const URI = process.env.DB_URI;
const option = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
export function connect() {
mongoose.connect(URI, option);
mongoose.connection.on("error", (err) => {
console.log("Could not connect to MongoDB");
console.log(err);
});
mongoose.connection.on("open", () => {
console.log("Connected to MongoDB!");
});
}
Notice the DB_URL
is an environment variable that stores the connection URI from the previous step.